package com.bxd.baodan.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.fragment.GuideFragment;
import com.bxd.baodan.fragment.MainBDFragment;
import com.bxd.baodan.fragment.MainGWFragment;
import com.bxd.baodan.fragment.MainSettingFragment_;
import com.bxd.baodan.fragment.ProductCenterFragment;
import com.bxd.baodan.probe.Probe;
import com.bxd.baodan.service.GetuiPushIntentService;
import com.bxd.baodan.service.GetuiPushService;
import com.bxd.baodan.update.UpdateChecker;
import com.bxd.baodan.util.AppManager;
import com.bxd.baodan.util.DialogUtil;
import com.bxd.baodan.util.LogUtil;
import com.bxd.baodan.util.LoginIMUtil;
import com.bxd.baodan.util.MsgUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.SpUtil;
import com.bxd.baodan.util.Utils;
import com.bxd.baodan.widget.IosDialog;
import com.igexin.sdk.PushManager;
import com.tencent.TIMManager;
import com.tencent.TIMMessage;
import com.tencent.TIMMessageListener;
import com.tencent.TIMUserStatusListener;
import com.testin.agent.TestinAgent;
import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengUpdateAgent;

import java.util.List;


@SuppressLint("NewApi")
public class MainActivity extends BaseActivity implements OnClickListener {


    private FragmentManager fragmentManager;

    private MainBDFragment fragment_1;//首页
    private MainGWFragment fragment_2;//保问
    public ProductCenterFragment fragment_3;
    private MainSettingFragment_ fragment_4;
    private BroadcastReceiver receiveBroadCast;
    private ImageView tab_iv_1, tab_iv_2,
            tab_iv_3, tab_iv_4;

    private TextView tab_tv_1, tab_tv_2, tab_tv_3, tab_tv_4;

    public int productPosition = -1;

    public boolean hasUnRead;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        isFirst();
        hideBar();

        fragmentManager = getSupportFragmentManager();
        initTabView();
        initIMListener();


        getLaunchStat();
        if (LoginInfo.getInstance(getApplicationContext()).getUser().getU_id() != null) {
            initPush();
        }
        // 第一次登陆所执行的操作

        initTabIndicator();

        //获取规划师id并存储.
        getPlanerId();
        // 友盟更新
        UmengUpdateAgent.update(this);
        //版本更新检测
        //fixme 去掉注释
        UpdateChecker.checkForDialog(MainActivity.this, false);
        TestinAgent.init(this, "2c5b72a2e87026636475b35ac135d7c3",
                Utils.getAppMetaData(this, "UMENG_CHANNEL"));

        showChatIcon();

        initBroadCastReceiver();
        //探针项目情动时间应大于一天
        startProbe();


    }





    //轮播跳转具体界面用
    public void gotoActivity(String actname) {
        String actPrex = "com.bxd.baodan.activity.";
        Class<?> ass = null;
        try {
            ass = Class.forName(actPrex + actname);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        if (ass != null) {
            Intent intent = new Intent(this, ass);
            startActivity(intent);
        }
    }

    private void startProbe() {

        long preTime = SpUtil.getInstance().getLong("currentTime");
        if (System.currentTimeMillis() - preTime > 24 * 60 * 60 * 1000) {
            upLoadProbe();
        }
    }

    // FIXME: 18/1/30 修改探针逻辑,登录就传
    private void upLoadProbe() {
        SpUtil.getInstance().savaLong("currentTime", System.currentTimeMillis());
        if (LoginInfo.getInstance().isLogin()) {
            String account = LoginInfo.getInstance().getAccount();
            Probe.getProData(this, account);
        } else {
            Probe.getProData(this, "");
        }
    }


    /**
     * 初始化推送
     */
    public void initPush() {

        PushManager.getInstance().initialize(getApplicationContext(), GetuiPushService.class);
        // com.getui.demo.DemoIntentService 为第三方自定义的推送服务事件接收类
        //   如果调用了registerPushIntentService方法注册自定义IntentService，则SDK仅通过IntentService回调推送服务事件；
        // 如果未调用registerPushIntentService方法进行注册，则原有的广播接收器仍然可以继续使用。
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), GetuiPushIntentService.class);
        String cid = PushManager.getInstance().getClientid(getApplicationContext());
        String alias = "wenwen" + getUserid();
        PushManager.getInstance().bindAlias(this, alias);
        if (LoginInfo.getInstance(MainActivity.this).isLogin()) {
            NetUtil netUtil = new NetUtil(MainActivity.this,
                    JsonApi.UPDATE_TOKEN);
            netUtil.setParams("deviceToken", cid);
            netUtil.postRequest("", new NetUtil.RequestStringListener() {
                @Override
                public void onComplete(String result) {
                    LogUtil.e("initPush--上传token到服务器成功");
                }
            });
        }
    }

    public void initTabView() {
        tab_iv_1 = getImageView(R.id.tab_iv_1);
        tab_iv_2 = getImageView(R.id.tab_iv_2);
        tab_iv_3 = getImageView(R.id.tab_iv_3);
        tab_iv_4 = getImageView(R.id.tab_iv_4);
        tab_tv_1 = getTextView(R.id.tab_tv_1);
        tab_tv_2 = getTextView(R.id.tab_tv_2);
        tab_tv_3 = getTextView(R.id.tab_tv_3);
        tab_tv_4 = getTextView(R.id.tab_tv_4);
    }


    private void initIMListener() {
        LoginIMUtil imUtil = new LoginIMUtil(MainActivity.this);
        imUtil.initIM();
        imUtil.loginIM();
        imUtil.setCallback(new LoginIMUtil.Callback() {
            @Override
            public void next() {
                sendBroadcast(new Intent(Constant.IM_LOGIN_SUCCESS));
            }
        });

        //互踢下线逻辑
        TIMManager.getInstance().setUserStatusListener(new TIMUserStatusListener() {
            @Override
            public void onForceOffline() {
                new IosDialog(AppManager.getInstance().currentActivity()).builder().setTitle("退出当前账号")
                        .setMsg("您的账户在其它设备上登录")
                        .setPositiveButton("重新登录", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                LoginInfo.getInstance(App.getContext()).cancelLogin(App.getContext());
                                App.getContext().sendBroadcast(new Intent(Constant.ACTION_LOGIN_LOGINOUT));
                                startActivity(new Intent(MainActivity.this, LoginActivity.class));
                            }
                        }).setNegativeButton("退出", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LoginInfo.getInstance(App.getContext()).cancelLogin(App.getContext());
                        App.getContext().sendBroadcast(new Intent(Constant.ACTION_LOGIN_LOGINOUT));
                    }
                }).show();
            }

            @Override
            public void onUserSigExpired() {
                LogUtil.e("im登录过期: ");
            }
        });
    }


    public void getLaunchStat() {
        NetUtil netUtil = new NetUtil(MainActivity.this, Constant.LAUNCHSTAT);
        netUtil.setParams("uid", LoginInfo.getInstance(MainActivity.this)
                .getUser().getU_id());
        netUtil.setParams("password", LoginInfo.getInstance(MainActivity.this)
                .getUser().getPwd());
        netUtil.postRequest("", new NetUtil.DataListener() {
            @Override
            public void onComplete(String data) {

            }
        }); //不需要监听
    }


    /*
     * 判断是否是第一次登陆 所执行的操作
     */
    public void isFirst() {

        if (LoginInfo.getInstance(this).isFirst()) {
            showGuide();
        }
    }

    /**
     * 显示向导
     */
    private void showGuide() {
        //        GuideFragment2 fragment2 = new GuideFragment2();
        //        fragment2.show(getSupportFragmentManager(), "guide2");
        GuideFragment fragment = new GuideFragment();
        fragment.show(getSupportFragmentManager(), "guide");

        //        GuideVideoFragment videoFragment = new GuideVideoFragment();
        //        videoFragment.show(getSupportFragmentManager(), "guide");
    }

    private void initBroadCastReceiver() {
        receiveBroadCast = new ReceiveBroadCast();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.ACTION_RECEIVE_MSG);
        filter.addAction(Constant.ACTION_SUCCESS_LOGIN);
        filter.addAction(Constant.ACTION_LOGIN_LOGINOUT);
        filter.addAction(Constant.ACTION_MAIN_BAOWWEN);
        this.registerReceiver(receiveBroadCast, filter);
    }

    /**
     * 显示消息
     */
    public void showChatIcon() {
        TIMManager.getInstance().addMessageListener(new TIMMessageListener() {
            @Override
            public boolean onNewMessages(List<TIMMessage> list) {

                if (MsgUtil.getImUnread()) {
                    showRed();
                }

                return false;
            }
        });
    }


    class ReceiveBroadCast extends BroadcastReceiver {

        @Override
        public void onReceive(Context arg0, Intent arg1) {

            if (Constant.ACTION_RECEIVE_MSG.equals(arg1.getAction())) {
                showRed();
            } else if (Constant.ACTION_LOGIN_LOGINOUT.equals(arg1.getAction())) {
                showRed();
                updateShell();
                updateBD();
            } else if (Constant.ACTION_SUCCESS_LOGIN.equals(arg1.getAction())) {
                showRed();
                updateShell();
                upLoadProbe();
                updateBD();
            } else if (Constant.ACTION_MAIN_BAOWWEN.equals(arg1.getAction())) {
                setTabSelection(1);
            }
        }

    }

    private void updateBD() {
        if (fragment_1 != null) {
            fragment_1.initData();
        }
    }



    private void updateShell() {
        if (fragment_4 != null) {
            fragment_4.updateShell();
        }
    }

    private void unRegistReceiver() {
        this.unregisterReceiver(receiveBroadCast);
    }


    @Override
    protected void onDestroy() {
        unRegistReceiver();
        super.onDestroy();

    }


    long clickedTime;

    @Override
    public void onBackPressed() {
        exit();
    }

    // 双击退出应用
    private void exit() {
        long curTime = System.currentTimeMillis();
        if (curTime - clickedTime < 2000) {
            LoginInfo.getInstance(getApplicationContext()).close();
            DialogUtil.getInstance().cancelToast();
            super.onBackPressed();
            App.getContext().exit();

        } else {
            clickedTime = curTime;
            DialogUtil.getInstance().showToast(MainActivity.this, "再按一次退出应用");
        }
    }


    /**
     * 将所有的Fragment都置为隐藏状态。
     *
     * @param transaction 用于对Fragment执行操作的事务
     */
    private void hideFragments(FragmentTransaction transaction) {
        if (fragment_1 != null) {
            transaction.hide(fragment_1);
        }

        if (fragment_2 != null) {
            transaction.hide(fragment_2);
        }
        if (fragment_3 != null) {
            transaction.hide(fragment_3);
        }

        if (fragment_4 != null) {
            transaction.hide(fragment_4);
        }


    }

    /**
     * 注册底部tab
     */
    private void initTabIndicator() {
        LinearLayout main_menu_discover_area = getLinearLayout(R.id.tab_ly_1);
        LinearLayout main_menu_find_area = getLinearLayout(R.id.tab_ly_2);
        LinearLayout main_menu_find_product = getLinearLayout(R.id.tab_ly_3);
        LinearLayout main_menu_setting_area = getLinearLayout(R.id.tab_ly_4);

        main_menu_discover_area.setOnClickListener(this);
        main_menu_find_area.setOnClickListener(this);
        main_menu_find_product.setOnClickListener(this);
        main_menu_setting_area.setOnClickListener(this);
        setTabSelection(0);
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        int currentPage = 0;

        switch (arg0.getId()) {
            case R.id.tab_ly_1:
                currentPage = 0;
                break;
            case R.id.tab_ly_2:
                currentPage = 1;
                break;
            case R.id.tab_ly_3:
                currentPage = 2;
                break;
            case R.id.tab_ly_4:
                currentPage = 3;
                break;

        }
        setTabSelection(currentPage);
    }

    /**
     * 根据传入的index参数来设置选中的tab页。
     *
     * @param index 每个tab页对应的下标。0表示消息，1表示联系人，2表示动态，3表示设置。
     */
    public void setTabSelection(int index) {

        int color = R.color.green_lab;

        // 重置选中调用
        resetOtherTabs();

        //   initSystemBar(index == 0);
        // 开启一个Fragment事务
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        hideFragments(transaction);
        switch (index) {
            case 0:
                // 首页
                MobclickAgent.onEvent(App.getContext(), "v6_1_3_SY");
                tab_tv_1.setTextColor(getResources().getColor(color));
                tab_iv_1.setImageResource(R.drawable.tab_1_press);
                if (fragment_1 == null) {
                    fragment_1 =new MainBDFragment();
                    transaction.add(R.id.tab_content, fragment_1);
                  //  showPopAd(0);
                } else {
                    transaction.show(fragment_1);
                }


                break;

            case 1:
                // 保问
                MobclickAgent.onEvent(App.getContext(), "v6_1_3_BW");
                tab_tv_2.setTextColor(getResources().getColor(color));
                tab_iv_2.setImageResource(R.drawable.tab_2_press);

                if (fragment_2 == null) {
                    fragment_2 = new MainGWFragment();
                    transaction.add(R.id.tab_content, fragment_2);
                } else {
                    transaction.show(fragment_2);
                }
                break;

            case 2:
                // 产品
                MobclickAgent.onEvent(App.getContext(), "v6_1_3_CP");
                tab_tv_3.setTextColor(getResources().getColor(color));
                tab_iv_3.setImageResource(R.drawable.tab_3_press);

                if (fragment_3 == null) {

                    fragment_3 = ProductCenterFragment.getInstance(productPosition);
                    transaction.add(R.id.tab_content, fragment_3);
                   // showPopAd(2);
                } else {
                    transaction.show(fragment_3);
                }
                break;

            case 3:
                // 我的
                MobclickAgent.onEvent(App.getContext(), "v6_1_3_WD");
                tab_tv_4.setTextColor(getResources().getColor(color));
                tab_iv_4.setImageResource(R.drawable.tab_4_press);
                if (fragment_4 == null) {
                    fragment_4 = new MainSettingFragment_();

                    transaction.add(R.id.tab_content, fragment_4);

                } else {
                    transaction.show(fragment_4);

                }

                break;


            default:
                break;
        }
        transaction.commitAllowingStateLoss();

    }

    /**
     * 重置其他的Tab
     */
    private void resetOtherTabs() {

        int color = R.color.black_33;
        tab_tv_1.setTextColor(getResources().getColor(color));
        tab_tv_2.setTextColor(getResources().getColor(color));
        tab_tv_3.setTextColor(getResources().getColor(color));
        tab_tv_4.setTextColor(getResources().getColor(color));

        tab_iv_1.setImageResource(R.drawable.tab_1_normal);
        tab_iv_2.setImageResource(R.drawable.tab_2_normal);
        tab_iv_3.setImageResource(R.drawable.tab_3_normal);
        tab_iv_4.setImageResource(R.drawable.tab_4_normal);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (fragment_4 != null && !fragment_4.isHidden()) {
            fragment_4.onHiddenChanged(false);
        }
        if (fragment_1 != null && !fragment_1.isHidden()) {
            fragment_1.onHiddenChanged(false);
        }
    }

    private void showRed() {
        // TODO: 18/2/26 要改 红点原则
    }


}
